# -*- coding: utf-8 -*-
# @Time    : 2019/3/1 21:22
# @Author  : shaoeric
# @Email   : shaoeric@foxmail.com

import cv2
import os
import numpy as np
from Metric import Accuracy
import matplotlib.pyplot as plt

def get_detected_image(file, red_low, red_up, green_low, green_up, blue_low, blue_up, train=True):
    if train:
        path = 'train'
    else:
        path = 'test'

    # 读取原图片和检测图
    img = cv2.imread('{}/origin/{}'.format(path, file))
    ground = cv2.imread('{}/ground/{}'.format(path, file.replace('.jpg', '.png').replace('.jpeg', '.png')), cv2.IMREAD_GRAYSCALE)
    b,g,r = cv2.split(img)

    img2 = np.zeros(shape=(img.shape[0], img.shape[1]))  # 实例化一个等大小的白色图片
    img2[(b>=blue_low) * (b<=blue_up) * (r>=red_low) * (r<=red_up) * (g>=green_low) *(g<=green_up)] = 255  # 阈值内的改为白色255
    return img2, ground

def getACC(train=True):
    ACC = []
    FILE = []
    path = 'train'
    if not train:
        path = 'test'
    for file in os.listdir('{}/origin'.format(path)):
        img2, ground = get_detected_image(file,90, 255, 30, 220, 20, 200, train=train)
        acc = Accuracy(img2, ground).get_acc()
        ACC.append(acc)
        FILE.append(file)
    # min_acc = min(ACC)
    # max_acc = max(ACC)
    # print(FILE[ACC.index(min_acc)], min_acc)  # yamuna_erandathi.jpg 0.22055253623188406
    # print(FILE[ACC.index(max_acc)], max_acc)  # m(01-32)_gr.jpg 0.960375
    return ACC, FILE

def plot_acc(ACC, text, set='train', mode='RGB', x=5.5, y=0.8):
    plt.bar([i for i in range(len(ACC))], ACC)
    plt.title('{}-set skin detective Accuracy with {}'.format(set, mode))
    plt.xlabel('sample')
    plt.ylabel('accuracy')
    plt.text(x, y, text, fontsize=9)
    plt.show()

def main():
    # 训练集下的RGB
    ACC, _ = getACC()
    print('average and variance of acc in train-set with RGB',
          np.average(ACC), np.var(ACC))  # 训练集下的检测准确率 0.7304536027412066 0.04180718544671779
    plot_acc(ACC, text='average acc={}\nvar of acc={}'.format(round(np.average(ACC),4), round(np.var(ACC),4)), x=-1.8, y=0.92)

    # 测试集下的RGB
    ACC, _ = getACC(train=False)
    print('average and variance of acc in test-set with RGB',
          np.average(ACC), np.var(ACC))  # 0.6967125121525389 0.034009696429461646
    plot_acc(ACC, text='average acc={}\nvar of acc={}'.format(round(np.average(ACC),4), round(np.var(ACC),4)),set='test', x=4.8, y=0.85)